import React, { useState, useEffect, useRef } from 'react';
import { useRequest, useModel } from 'umi';
import { Row , Card, Image } from 'antd';
import { getMonitoringDevicInfo, getMonitoringPhase } from '@/services/deviceLive';

import moment from 'moment'
import ECharts from 'echarts-for-react';
import AlarmTable from '@/pages/monitoring/deviceAlarm';
import DeviceRunState from '@/pages/monitoring/deviceRunState';
import {transducerTripcode} from '@/utils/alarmcode-enum';

import Monitor from '../components/Monitoring';
import styles from './index.less';

import slg from '@/assets/img/img/slg1.png';
import item1 from '@/assets/img/img/2item1-1.png';
import item2 from '@/assets/img/img/item8.png';
import item3 from '@/assets/img/img/2item1-3-1.png';
import item4 from '@/assets/img/img/2item2.png';
import item5 from '@/assets/img/img/2item1-3-2.png';
import item6 from '@/assets/img/img/item6.png';



const details: React.FC = (props: any) => {
  const { params } = props.match;
 
  const second = useRequest(() => {
    return getMonitoringPhase({...params,type:1});
  }, {
    pollingInterval: 3000,
    pollingWhenHidden: false
  });

  const [deviceInfo, setDeviceInfo] = useState<API.DeviceItem>({});
  const [runningData, setRunningData] = useState({});


  const [chartIndex, setChartIndex] = useState(4);

  const [onLineBackgroundColor, setOnLineBackgroundColor] = useState('#8ca1aa');
  const [alarmBackgroundColor, setAlarmBackgroundColor] = useState('red');


  const { initialState,setInitialState } = useModel('@@initialState');
  const { mySocket } = initialState || {};

  if (mySocket&&mySocket.ws.readyState==1){
    mySocket.send(params.id);
    mySocket.onmessage =async function (e) {
     // console.log(`onmessage: ${e.data}`);
      //排除心跳数据
      if ("heartbeat" != e.data&&e.data.indexOf("RunningData")!=-1) {
        onMessage(e);
      }else if ("heartbeat" != e.data&&e.data.indexOf("AlarmData")!=-1) {
        const data = JSON.parse(e.data);
        await setInitialState((s) => ({ ...s, alarmNotices: data.AlarmData }));
      }
    };
  }






  const onMessage = (e:any) => {
    const message = JSON.parse(e.data);
  
   // const runningData = {...message.RunningData, ...message.ReliabilityData}
    const rData = message.RunningData||{};
    console.log(rData)
    if(rData.deviceId!=params.id){
     return;
    }
    rData.acquisitionTime = moment().format("YYYY-MM-DD HH:mm:ss");
    if(runningData?.online==0&&rData?.online==1){
       go();
    }
    if(runningData?.alarm==0&&rData?.alarm==1){
        go1();
    }
    setRunningData(rData);
  }


  useEffect(() => {
    const setSelectData = async () => {
      var details = await getMonitoringDevicInfo(params);
    
      setRunningData(details.runningData);
      setDeviceInfo(details.deviceInfo);
      if(details?.runningData?.online==1){
        await go();
      }
      if(details?.runningData?.alarm==1){
        await  go1();
      }
   
    }
    setSelectData();
 
  }, []);

  const sleep = (t) => {
    return new Promise((res,rej)=>{
        setTimeout(res,t)
    })
}

  async function  go() {
    setOnLineBackgroundColor("yellow");
    await sleep(200)
    setOnLineBackgroundColor("#19377f");
    await  sleep(200)
    go()
}


async function  go1() {
  setAlarmBackgroundColor("red");
  await sleep(300)
  setAlarmBackgroundColor("#19377f");
  await  sleep(300)
  go1()
}

function  getJingDu() {
  let a=runningData?.closedLoopFeedback||0;
  let b=runningData?.closedLoopSetting==null||runningData?.closedLoopSetting==0?1:runningData?.closedLoopSetting;
  let c=a/b*100;
  return c.toFixed(2);
}


let  transducerTripcodeArray=  Object.entries(transducerTripcode);

  const option2 = {
    color: ["red"],
    grid: {
      top: 50,
      left: 60,
      right: 50,
      bottom: 30
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
    
      type: 'category',
      boundaryGap: false,
      data: second.data?.phaseTime,
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    yAxis: {
      type: 'value',
     // min:0,  //取0为最小刻度
      // max: 60, //取100为最大刻度
      axisLabel: {
        formatter: '{value}'
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    series: second.data?.data
  };
 
  const option3 = {
    color: ["green"],
    grid: {
      top: 50,
      left: 60,
      right: 50,
      bottom: 30
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
    
      type: 'category',
      boundaryGap: false,
      data: second.data?.phaseTime,
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    yAxis: {
      type: 'value',
      scale:true,
     min:0,  //取0为最小刻度
  
 
      axisLabel: {
        formatter: '{value}'
      },
      minInterval:1,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    series: second.data?.data1
  };
 

  

  
  return (
    <div className={styles.main} key={1}>
   
     <div  className={styles.flexBetween} style={{    marginRight: '10px',    alignItems: 'end'}}>
     <div className={styles.flexBetween} style={{flex:5,    alignItems: 'end',minWidth:'650px',width: 'auto'}}>
        <div style={{flex:  1}}> 
          <div  className={styles.flex}>  
            <Image    src={slg}  preview={false} />
            <div className={styles.deviceInfo} >
                <div>
                  <span  className={styles.title} > {deviceInfo?.deviceName||'--'} </span>
                  <span className={styles.updateTimeText} > (最新同步时间：{runningData?.acquisitionTime||'--'})</span>
                </div>
                <div className={styles.flexBetween} > 
                  <div>  
                    <span>设备位号：{deviceInfo?.deviceNo||'--'} </span>  
                    <span>&nbsp;  安装位置：{deviceInfo?.areaName||'--'}{deviceInfo?.devicePosition}</span>
                  </div>
                  <div>最新维保日期:{deviceInfo?.latestMaintenanceTime}</div>
                </div>  
            </div>
          </div>
          </div>

      </div>
      <div  className={styles.flexBetween} style={{flex:3}}>
        <div  className={ [styles.flexBetween, styles.stateL].join(' ')}>
          <div>
            <div  className={runningData?.FWD==1||runningData?.fwd==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>正转运行中</span>
          </div>
          <div>
            <div  className={runningData?.REV==1||runningData?.rev==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>反转运行中</span>
          </div>
          <div>
          <div  className={runningData?.STOP==1||runningData?.stop==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>停机中</span>
          </div>
        </div>
        <div  className={ [styles.flexBetween, styles.stateR].join(' ')}>
          <div>
          <div  className={runningData?.running==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>运行</span>
          </div>
      
          <div>
            <div  className={runningData?.alarm==1? [styles.yuan, styles.bgRed].join(' '):styles.yuan} ></div>
            <span>故障</span>
          </div>
          <div>
            <div  className={runningData?.online==1? [styles.yuan, styles.bgYellow].join(' '):styles.yuan} style={{backgroundColor:onLineBackgroundColor}}></div>
            <span>通讯</span>
          </div>
        </div>
      </div>
     </div>
     <div  className={styles.flexBetween} style={{  margin:  '12px 0 30px 0', alignItems:'start'}}>
      <div  style={{flex:5}}>
        <div className={styles.flex} >
         <div  className={styles.dataItem} style={{    marginLeft: '0px'}}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item1}  preview={false} /> <span className={styles.topRight} >设定频率{runningData?.settingFrequency}Hz</span></div>

            <div style={{margin: '0 0 -2px 10px',color:'rgb(64 255 255)',    marginTop: '-3px'}}  className={styles.flex}><span><span  className={styles.nameItalic} >F</span>a</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.operatingFrequency}</span>Hz</div></div>
            <div className={styles.attribute}  >运行频率</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item2}  preview={false} /> <span className={styles.topRight} ></span></div>
            
            <div style={{margin: '0 0 -2px 10px',color:'rgb(64 255 255)',    marginTop: '-3px'}}  className={styles.flex}><span><span  className={styles.nameItalic} >U</span>i</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.busVoltage}</span>V</div></div>
            <div className={styles.attribute} >母线电压</div>
          </div>
        
            <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item3}  preview={false} /> <span className={styles.topRight} ></span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.outputVoltage}</span><span className={styles.unit}>V</span></div>
              <div className={styles.attribute}>输出电压</div>
            </div>
        </div>
        
        <div className={styles.flex} >
          <div  style={{flex:2,   }}>
            <div  className={styles.dataItem}  style={{height: '236px',margin:'0 6px 0 0'}}> 
                <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item4}  preview={false} /> <span className={styles.topRight} ></span></div>
              
               
                <div className={styles.flex} style={{margin:'5px 0 18px'}}>
                  <div className={styles.center}><Monitor name="闭环设定" value={runningData?.closedLoopSetting||0} idName="chart1" style={{ height: 150, width: 150 }} /></div> 
                  <div  className={styles.center}><Monitor name="闭环反馈"  value={runningData?.closedLoopFeedback||0}  idName="chart2" style={{ height: 150, width: 150 }} /></div> 
                    <div  className={styles.center}><Monitor  name="控制精度"  value={getJingDu()}  idName="chart3" style={{ height: 150, width: 150}} /></div> 
                  </div>
               
                  
                  <div className={styles.attribute}  >闭环控制</div>
            
              </div>
          </div>
          <div  style={{flex:1}}>
          <div  className={styles.dataItem} style={{    marginBottom: '10px'}} >
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item5}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.outputCurrent}</span><span className={styles.unit}>A</span></div>
            <div className={styles.attribute}>输出电流</div>
          </div>
          <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item6}  preview={false} /> <span className={styles.topRight} ></span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.outputPower}</span><span className={styles.unit}>%</span></div>
              <div className={styles.attribute}>输出功率</div>
            </div>
          </div>
         {/*
            <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={moxing}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div><span className={styles.data} >{runningData?.rotationalVelocity}</span><span className={styles.unit}>RPM</span></div>
            <div className={styles.attribute}>运行转速</div>
          </div>  <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={moxing}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div><span className={styles.data} >{runningData?.outputTorque}</span><span className={styles.unit}>RPM</span></div>
            <div className={styles.attribute}>输出转矩</div>
          </div> */}
           
          
        </div>
       
        {/* <div className={styles.flexBetween} >
          <div  style={{flex:1}}>
            <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={moxing}  preview={false} /> <span className={styles.topRight} >闭环设定{runningData?.closedLoopSetting}%</span></div>
              <div><span className={styles.data} >{runningData?.closedLoopFeedback}</span><span className={styles.unit}>%</span></div>
              <div className={styles.attribute}>闭环反馈</div>
            </div>
          </div>
          <div  style={{flex:1}}>
          </div>
          <div  style={{flex:1}}>
            <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={moxing}  preview={false} /> <span className={styles.topRight} ></span></div>
              <div><span className={styles.data} >{runningData?.outputPower}</span><span className={styles.unit}>%</span></div>
              <div className={styles.attribute}>输出功率</div>
            </div>
          </div>
        </div> */}
      </div>
      <div className={styles.flex} style={{flex:3}}>
        <Card  style={{flex:1}} className={ styles.alarmBox}  >
          <div className={styles.title}>报警指示</div>
          <div className={styles.content} >
          {transducerTripcodeArray.map((item ,index) => {
         
            if(index%2==0){
              return( <div className={styles.flexBetween} >
                <div style={{flex:1}} className={styles.flex}>
                  <div className={styles.yuan}   style={runningData?.alarmCode==item[0]?{backgroundColor:alarmBackgroundColor}:{}}></div>
                  <span className={styles.baojingText}>{item[1]}</span>
                </div>
                {transducerTripcodeArray.length%2==0||transducerTripcodeArray.length-1>index? <div className={styles.flex} style={{flex:1}}>
                  <div className={styles.yuan}   style={runningData?.alarmCode==transducerTripcodeArray[index+1][0]?{backgroundColor:alarmBackgroundColor}:{}}></div>
                  <span className={styles.baojingText}>{transducerTripcodeArray[index+1][1]}</span>
                </div>:<div className={styles.flex} style={{flex:1}}></div>}
              </div>)
            }
            })}
         </div>
        </Card>
        
      </div>
      </div>
    
     
     <Row key={6}>
        <div className={styles.tabsTitle}>
           <a className={chartIndex != 4 ? styles.a1 : [styles.a1, styles.tabcheck1].join(' ')} onClick={() => setChartIndex(4)} > 运行状态</a>
            <div className={ chartIndex != 4 ? styles.a1after : [styles.a1after, styles.a1afterCheck].join(' ') }></div>
          <a className={chartIndex!=1?styles.a2:[styles.a2,styles.tabcheck].join(' ')}   onClick={()=>setChartIndex(1)} >运行频率趋势分析</a>
          <a className={chartIndex!=2?styles.a2:[styles.a2,styles.tabcheck].join(' ')}   onClick={()=>setChartIndex(2)}> 输出电流趋势分析</a>
          <a className={chartIndex!=3?styles.a3:[styles.a3,styles.tabcheck].join(' ')}  onClick={()=>setChartIndex(3)}> 报警信息</a>
        </div>
        <Card  className={ styles.modalItem} title={null} style={{width:"100%"}} >
          <ECharts  style={{display:chartIndex==1?'block':'none'}}   option={option2} />
          <ECharts  style={{display:chartIndex==2?'block':'none'}} option={option3} />
          <AlarmTable deviceId={params.id} display={chartIndex==3?'block':'none'}></AlarmTable>
          <DeviceRunState  deviceId={params.id} display={chartIndex==4?'block':'none'} />
          </Card>
        
      </Row>
 
    </div>
  );
};

export default details;